<template>
  <div class="form-content">
    <div class="small-title">
      基础信息
    </div>
    <div class="form-item">
      <div class="inp-name">授课地点</div>
      <div>
        <el-select v-model="courseFormState.schoolId"  placeholder="请选择" size="large">
          <el-option
            v-for="item in schollOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程人数</div>
      <div>
        <el-input placeholder="" v-model="courseFormState.studentNum" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程名称</div>
      <div>
        <el-input v-model="courseFormState.name" placeholder="">
        </el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程类型</div>
      <div>
        <el-select v-model="courseFormState.courseCategoryId" @change="courserChange" placeholder="请选择" size="large">
          <el-option
            v-for="item in courseOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">学科分类</div>
      <div>
        <el-select v-model="courseFormState.classifyId" placeholder="请选择" size="large">
          <el-option
            v-for="item in classifyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">有效期</div>
      <div>
        <el-input v-model="courseFormState.validity" placeholder="" oninput="value=value.replace(/[^\d]/g,'')">
          <template #append>日</template>
        </el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程描述</div>
      <div>
        <el-input type="textarea" placeholder="" v-model="courseFormState.VDesc"></el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程介绍</div>
      <div>
        <el-input type="textarea" placeholder="" v-model="courseFormState.courseParticulars"></el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程亮点</div>
      <div>
        <el-input type="textarea" placeholder="" v-model="courseFormState.excellence"></el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">视频</div>
      <div>
        <el-button type="primary" plain @click="changeVideoUpload" v-if="courseId && videoUrl && !isDeleteVideo">删除视频</el-button>
        <el-button type="primary" plain @click="videoUpload" v-else>上传视频</el-button>
      </div>
    </div>
    <div class="form-item">
      <div class="video_url" v-if="videoUrl">
        <VideoPlay
        :src="videoUrl"
        />
      </div>
    </div>
    <div class="small-title">
      排课方式
    </div>
    <div class="form-item">
      <div class="inp-name">上课次数</div>
      <div>
        <el-input @blur="changeNumBlur(courseFormState.times)" v-model="courseFormState.times" oninput="value=value.replace(/[^\d]/g,'')" placeholder="">
          <template #append>次</template>
        </el-input>
      </div>
    </div>
    <div class="form-item">
      <div class="inp-name">课程时长</div>
      <div>
        <el-input  @blur="changeNumBlur(courseFormState.VSchedule)" v-model="courseFormState.VSchedule" oninput="value=value.replace(/[^\d^\.]/g,'')" placeholder="">
          <template #append>分钟</template>
        </el-input>
      </div>
    </div>
    <div class="small-title">
      报名价格
    </div>
    <div class="form-item">
      <div class="inp-name">报名价格</div>
      <div>
        <el-input v-model="courseFormState.nowPrice" oninput="value=value.replace(/[^\d^\.]/g,'')" placeholder="">
        </el-input>
      </div>
    </div>
    <div class="tip" v-if="!courseFormState.nowPrice">
      *请输入报名价格
    </div>
    <div class="form-item">
      <div class="inp-name">课时单价</div>
      <div>
        <el-input v-model="courseFormState.unitPrice"  oninput="value=value.replace(/[^\d^\.]/g,'')" placeholder="">
        </el-input>
      </div>
    </div>
    <div class="tip" v-if="!courseFormState.unitPrice">
      *请输入课时单价
    </div>
    <div class="form-item">
      <div class="inp-name">班级原价</div>
      <div>
        <el-input v-model="courseFormState.price" oninput="value=value.replace(/[^\d^\.]/g,'')" placeholder="">
        </el-input>
      </div>
    </div>
    <div class="tip line" v-if="!courseFormState.price">
      *请输入班级原价
    </div>
    <div class="small-title">
      工具
    </div>
    <div class="form-item">
      <div class="inp-name">工具</div>
      <!-- <div v-if="courseFormState.tools.length > 0">
        <div class="good-list">
          <div class="item" v-for="(item, index) in courseFormState.tools" :key="index">
            <div>{{ item.name }}</div>
            <div class="icon" @click="removeCourseGoods(index)">
              <el-icon><Close/></el-icon>
            </div>
          </div>
        </div>
      </div> -->
      <div>
        <div class="tool-list">
          <div class="item p-flex p-ai-c m-b-10" v-for="(item, index) in courseFormState.tools" :key="index">
            <div style="flex: 3;">
              <el-input placeholder="请输入工具名称" v-model="item.toolName"></el-input>
            </div>
            <div class="m-l-10" style="flex: 1;">
              <el-input placeholder="请输入价格" v-model="item.toolCost" oninput="value=value.replace(/[^\d^\.]/g,'')"></el-input>
            </div>
            <div class="m-l-10">
              <el-button type="primary" plain :icon="Plus" @click="changeTool('Plus', index)" />
              <el-button type="danger" plain :icon="Minus" @click="changeTool('Minus', index)" />
            </div>
          </div>
        </div>
        <el-button type="primary" plain :icon="Plus" @click="changeTool('Plus', -1)" v-if="courseFormState.tools.length === 0"/>
      </div>
    </div>
    <!-- 第一期因没有管理工具的页面功能，先以手动添加的形式 -->
    <!-- <div class="form-item good-btn">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="addGoods">
					添加工具
				</el-button>
      </div>
      <div class="tip">
        *有学生报名"商品"不能修改
      </div>
    </div> -->
    <div class="small-title">
      课程大纲
    </div>
    <div class="form-item">
      <div class="inp-name">课程大纲</div>
      <div class="table">
        <div class="title"> 
          <div>课次</div>
          <div>大纲内容</div>
        </div>
        <div class="content-list">
          <div class="table-item" v-for="(item, index) in courseFormState.outlines" :key="index">
            <div>{{ index+1 }}</div>
            <div>
              <el-input placeholder="在此输入大纲内容" v-model="item.outline"></el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-upload
      ref="upload"
      action="fakeaction"
      accept=".mp4"
      style="display: none;"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :http-request="httpRequest"
    ></el-upload>

    <SelectGoods ref="selectGoodsRef" @comfirm="comfirm" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance, defineExpose } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Close, Minus, Plus } from '@element-plus/icons-vue'
import SelectGoods from './../../components/selectGoods.vue'
import VideoPlay from './video-play.vue';
import useTabs from '@/utils/useTabs';

const { proxy } = getCurrentInstance()
const route = useRoute()
const courseId = ref(null)
onMounted(() => {
  courseId.value = route.params.id;
  if (courseId.value) {
    getCourseDetails(courseId.value)
  }
  getDropdown()
  getCategory()
})

// 获取课程类型
const getCategory = async()=>{
  const { code, data } = await proxy.$API.public.getCategory.get();
  if (code == 200) {
    courseOptions.value = data
  }
}

// 获取学科分类
const getClassify = async(id)=>{
  const params = {categoryId: id}
  const { code, data } = await proxy.$API.public.getClassify.get(params);
  if (code == 200) {
    classifyOptions.value = data
  }
}

// 获取课程详情
const getCourseDetails = (courseId) => {
  const data = {courseId: courseId}
  proxy.$API.course.updateGetDetail.get(data).then(res => {
    console.log(res);
    if (!res.data.tools) {
      res.data.tools = []
    }
    courseFormState.value = res.data
    courseFormState.value.VDesc = res.data.vdesc
    courseFormState.value.VSchedule = res.data.vschedule
    // 视频
    videoUrl.value = res.data.propagandize
    courseFormState.value.propagandize = null
    if (res.data.name) {
      // 修改名称
      useTabs.setTitle(res.data.name + '-编辑课程')
    }
  })
}

// 获取校区下拉列表
const getDropdown = () => {
  proxy.$API.clue.dropdown.get().then(res => {
    schollOptions.value = res.data
  })
}
const selectGoodsRef = ref(null)

// 课程类型下拉框
const courseOptions = ref([])
// 学科分类下拉框
const classifyOptions = ref([])

// 选择课程类型
function courserChange(val) {
  classifyOptions.value = []
  courseFormState.value.classifyId = ""
  getClassify(val)
}

// 校区下拉框
const schollOptions = ref([])

// const courseFormData = reactive({
//   formData: new FormData()
// })
const courseFormState = ref({
  schoolId: "",   //校区ID
  studentNum: "",  //课程人数
  name: "",   //课程名称
  courseCategoryId: "",   // 课程类型ID
  classifyId: "",   //学科分类id
  validity: "",   //有效期
  VDesc:"",   //课程描述
  courseParticulars:"",   //课程内容
  excellence:"",  //课程亮点
  times: 1,     //课次
  VSchedule: 60,   //课程时长
  nowPrice: "",  // 报名价格
  unitPrice: "",  //课时单价
  price: "",   //原价
  tools: [],   //工具列表
  outlines: [{outline: ""}],    //大纲
  propagandize: null     //视频
})

// 上课次数、课程时长失去焦点
function changeNumBlur(val) {
  console.log(typeof(val));
  handIsNum1()
  handlerClassTime()
  handCurriculum()
}

// 处理上课次数是否合规
function handIsNum1() {
  if (!courseFormState.value.times || courseFormState.value.times < 1) {
    courseFormState.value.times = 1
  }else{
    courseFormState.value.times = Math.round(courseFormState.value.times)
  }
}
// 处理课程时长是否合规
function handlerClassTime() {
  if (courseFormState.value.classTime) {
    courseFormState.value.classTime = Math.round(courseFormState.value.classTime)
  }
}
// 大纲内容行数
function handCurriculum() {
  if(courseFormState.value.times != courseFormState.value.outlines.length){
    courseFormState.value.outlines = []
    for (let i = 0; i < courseFormState.value.times; i++) {
      courseFormState.value.outlines.push({outline: ""})
    }
  }
}

// 移除课程商品
function removeCourseGoods(index) {
  courseFormState.value.tools.splice(index, 1)
}

// 打开添加商品弹窗
function addGoods() {
  const arr = JSON.parse(JSON.stringify(courseFormState.value.tools))
  selectGoodsRef.value.openDialog(arr)
}

// 添加、移除工具
function changeTool(type, index) {
  if (type === 'Plus') {
    if (index === -1) {
      courseFormState.value.tools.push({toolName: "", toolCost: ""})
    }else{
      courseFormState.value.tools.splice(index+1, 0, {toolName: "", toolCost: ""})
    }
  }else{
    courseFormState.value.tools.splice(index, 1)
  }
}

const upload = ref(null)

// 记录修改的视频的URL
const delVideoUrl = ref(null) 

// 是否有点击删除视频
const isDeleteVideo = ref(false)

// 删除视频
function changeVideoUpload() {
  isDeleteVideo.value = true
  delVideoUrl.value = videoUrl.value
  videoUrl.value = ""
}
// 上传视频
function videoUpload() {
  const uploadRef = upload.value.$refs.uploadRef
  uploadRef.$refs.inputRef.click();
}
// 上传前
function beforeUpload(file){
  console.log('file', file);
}
// 上传成功
function uploadSuccess(res, file){
  console.log('uploadSuccess', file);
}
const videoUrl = ref("")
// 自定义上传
function httpRequest(option){
  // courseFormData.formData.append('file', option.file)
  courseFormState.value.propagandize = option.file
  blobToBase64(option.file)
}

// file转base64
function blobToBase64(file){
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = function (o) {
    videoUrl.value = o.target.result
  }
}

function comfirm(arr) {
  courseFormState.value.tools = arr
}

defineExpose({courseFormState, delVideoUrl})

</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
